#include <iostream>
#include <functional>
#include <unordered_map>
#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/TcpConnection.h"

class TranslateServer
{
public:
    TranslateServer(int port)
    :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port)
            , "TranslateServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage, this, std::placeholders::_1,
        std::placeholders::_2, std::placeholders::_3));
    }
    void start()
    {
        // 开始事件监听
        _server.start();
        // 开始事件监控
        _baseloop.loop();
    }
private:
    // 新连接建立成功时的回调函数
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if (conn->connected() == true)
            std::cout << "新连接建立成功！" << std::endl;
        else
            std::cout << "新连接关闭！" << std::endl;
    }
    std::string translate(const std::string& str)
    {
        static std::unordered_map<std::string, std::string> dict_map = {
            {"hello", "你好"},
            {"apple", "苹果"},
            {"happy", "开心"}
        };
        auto it = dict_map.find(str);
        if (it == dict_map.end())
            return "没有找到！";
        return it->second;
    }
    // 通信连接收到请求时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        // 把数据从buf中取出
        std::string str = buf->retrieveAllAsString();
        // 翻译
        std::string resp = translate(str);
        // 响应客户端
        conn->send(resp);
    }
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    TranslateServer server(8080);
    server.start();

    return 0;
}